package com.kye.express.business.score;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityScoreBinding;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.logistics.LogisticsDriverInfoBean;
import com.kye.model.bean.user.User;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;

public class ScoreActivity extends BaseAppCompatActivity implements ScoreContract.ScoreView {

    private static final String TAG_SCORE_TYPE = "TAG_SCORE_TYPE";
    private static final String TAG_SCORE_CODE = "TAG_SCORE_CODE";

    private ActivityScoreBinding binding;
    private ScoreContract.ScorePresenter presenter;
//    private OrderDetailResultBean orderDetailResultBean;
    private String code;
    private User userInfo;
    private Dialog dialog;
    private MultiTypeAdapter adapter;
    private MultiTypeAdapter adapterSuccess;
    private List<ScoreTagModel> scoreTagModelsLevel1;
    private List<ScoreTagModel> scoreTagModelsLevel2;
    private List<ScoreTagModel> scoreTagModelsLevel3;
    private List<ScoreTagModel> scoreTagModelsLevel4;
    private List<ScoreTagModel> scoreTagModelsLevel5;
    private List<ScoreTagModel> scoreTagModelsLevel0 = new ArrayList<>();
    private List<ScoreTagModel> scoreTagSelected;
    private ScoreType postScore;
    private boolean disableScore;
    private LogisticsDriverInfoBean logisticsDriverInfoBean;

    public static Intent newStartIntentForScoreOrder(Context context, String code) {
        Intent intent = new Intent(context, ScoreActivity.class);
        intent.putExtra(TAG_SCORE_TYPE, ScoreType.TYPE_ORDER);
        intent.putExtra(TAG_SCORE_CODE, code);
        return intent;
    }

    public static Intent newStartIntentForScoreWayBill(Context context, String code) {
        Intent intent = new Intent(context, ScoreActivity.class);
        intent.putExtra(TAG_SCORE_TYPE, ScoreType.TYPE_WAYBILL);
        intent.putExtra(TAG_SCORE_CODE, code);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            code = savedInstanceState.getString(TAG_SCORE_CODE);
        } else {
            code = getIntent().getStringExtra(TAG_SCORE_CODE);
            postScore = (ScoreType) getIntent().getSerializableExtra(TAG_SCORE_TYPE);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_score);
        presenter = new ScoreContract.ScorePresenter();
        initToolbar();
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.getString(TAG_SCORE_CODE, code);
        outState.putSerializable(TAG_SCORE_TYPE, postScore);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar() {
        setSupportActionBar(binding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initViews(Bundle savedInstanceState) {
        ChipsLayoutManager spanLayoutManagerHistory = ChipsLayoutManager.newBuilder(this)
                .setOrientation(ChipsLayoutManager.STRATEGY_CENTER)
                .build();
        ChipsLayoutManager spanLayoutManagerHistory2 = ChipsLayoutManager.newBuilder(this)
                .setOrientation(ChipsLayoutManager.STRATEGY_CENTER)
                .build();
        adapter = new MultiTypeAdapter();
        adapterSuccess = new MultiTypeAdapter();
        adapter.register(ScoreTagModel.class, new ScoreTagViewBinder());
        adapterSuccess.register(ScoreTagModel.class, new ScoreTagViewBinder());
        binding.scoreTags.setLayoutManager(spanLayoutManagerHistory);
        binding.scoreTags.setAdapter(adapter);
        binding.scoreTagsSelected.setLayoutManager(spanLayoutManagerHistory2);
        binding.scoreTagsSelected.setAdapter(adapterSuccess);
    }

    private void initEvents(Bundle savedInstanceState) {
        binding.scoreStarts.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return disableScore;
            }
        });
        binding.scoreStarts.setOnRatingChangeListener(new MaterialRatingBar.OnRatingChangeListener() {
            @Override
            public void onRatingChanged(MaterialRatingBar ratingBar, float rating) {
                Logger.d("onRatingChanged : " + rating);
                binding.scoreCommit.setEnabled(rating > 0);
                presenter.showScoreRatingData(ratingBar, rating);
            }
        });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.scoreCommit)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        List<ScoreTagModel> scoreTagModels = (List<ScoreTagModel>) adapter.getItems();
                        String message = binding.scoreMessageInput.getText().toString();
                        int rating = (int) binding.scoreStarts.getRating();
                        presenter.postScore(postScore, userInfo, scoreTagModels, rating, message);
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        /**
         * 评分未完成或不成功
         */
        setResult(Activity.RESULT_CANCELED);
        binding.statusLayout.showLoadingView();
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        if (!user.isLogin()) {
            ToastManager.showCenterForShort("请先登录");
            finish();
            return;
        }
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getLogisticsDriverInfo(userInfo.getPhone(), code);
            }
        });
        presenter.getLogisticsDriverInfo(userInfo.getPhone(), code);
    }

    @Override
    public void getLogisticsDriverInfoSuccess(LogisticsDriverInfoBean logisticsDriverInfoBean) {
        this.logisticsDriverInfoBean = logisticsDriverInfoBean;
        binding.statusLayout.showContentView();
        // update driver info
        binding.name.setText(logisticsDriverInfoBean.getDriverName());
        binding.number.setText(logisticsDriverInfoBean.getDriverId());
        Glide.with(this)
                .load(logisticsDriverInfoBean.getDriverImage())
                .apply(new RequestOptions().fitCenter().placeholder(R.drawable.icon_driver_default_avatar).error(R.drawable.icon_driver_default_avatar))
                .into(binding.avatar);
    }

    @Override
    public void getLogisticsDriverInfoFailed(String msg) {
        ToastManager.showCenterForShort(msg);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void getLogisticsDriverInfoFailedNet(String msg) {
        ToastManager.showCenterForShort(msg);
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void updateScoreRatingTags(List<ScoreTagModel> scoreTagModels, int rating) {
        switch (rating) {
            case 0:
                binding.scoreDesc.setText("请评分");
                scoreTagModelsLevel0 = scoreTagModels;
                break;
            case 1:
                binding.scoreDesc.setText("非常不满意");
                scoreTagModelsLevel5 = scoreTagModels;
                break;
            case 2:
                binding.scoreDesc.setText("不满意");
                scoreTagModelsLevel4 = scoreTagModels;
                break;
            case 3:
                binding.scoreDesc.setText("一般");
                scoreTagModelsLevel3 = scoreTagModels;
                break;
            case 4:
                binding.scoreDesc.setText("比较满意");
                scoreTagModelsLevel2 = scoreTagModels;
                break;
            case 5:
                binding.scoreDesc.setText("非常满意");
                scoreTagModelsLevel1 = scoreTagModels;
                break;
        }
        adapter.setItems(scoreTagModels);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void postScoreSuccess(OpenApiResult<Object> result, String message) {
        disableScore = true;
        binding.scoreTags.setVisibility(View.GONE);
        binding.scoreMessageInput.setVisibility(View.GONE);
        binding.scoreCommit.setVisibility(View.GONE);
        if (scoreTagSelected != null && scoreTagSelected.size() > 0) {
            binding.scoreTagsSelected.setVisibility(View.VISIBLE);
            Observable.fromIterable(scoreTagSelected)
                    .doOnNext(new Consumer<ScoreTagModel>() {
                        @Override
                        public void accept(ScoreTagModel scoreTagModel) throws Exception {
                            scoreTagModel.setDisable(true);
                        }
                    })
                    .toList()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<ScoreTagModel>>() {
                        @Override
                        public void accept(List<ScoreTagModel> scoreTagModels) throws Exception {
                            adapterSuccess.setItems(scoreTagModels);
                            adapterSuccess.notifyDataSetChanged();
                        }
                    });
        } else {
            binding.scoreTagsSelected.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(message)) {
            binding.scoreMessagePost.setVisibility(View.GONE);
        } else {
            binding.scoreMessagePost.setVisibility(View.VISIBLE);
            binding.messagePosted.setText(message);
        }
        ToastManager.showCenterForLong(result.getMsg());
        /**
         * todo : 评分成功
         */
        setResult(Activity.RESULT_OK);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void postScoreFailed(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel1() {
        return scoreTagModelsLevel1;
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel2() {
        return scoreTagModelsLevel2;
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel3() {
        return scoreTagModelsLevel3;
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel4() {
        return scoreTagModelsLevel4;
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel5() {
        return scoreTagModelsLevel5;
    }

    @Override
    public List<ScoreTagModel> getScoreTagModelsLevel0() {
        return scoreTagModelsLevel0;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public void setScoreTagSelected(List<ScoreTagModel> scoreTagSelected) {
        this.scoreTagSelected = scoreTagSelected;
    }
}
